//
//  XDDetailsViewController.m
//  Le way walkers
//
//  Created by dlios on 15-5-14.
//  Copyright (c) 2015年 LTXZ. All rights reserved.
//

#import "XDDetailsViewController.h"
#import "XDDetails.h"
#import "XDPhotoTextViewController.h"
#import "NetworkHandle.h"
#import "UIImageView+WebCache.h"

#import "XDRecommendDateBaseManager.h"

@interface XDDetailsViewController ()<UICollectionViewDelegate,UICollectionViewDataSource, UICollectionViewDelegateFlowLayout, ChuanZHi>
@property(nonatomic,retain)UICollectionView *collectionView;
@property (nonatomic, retain) NSMutableArray *array;
@property (nonatomic, assign) NSInteger index_row;
@property (nonatomic,retain) XDRecommendDateBaseManager *dbManager;
@property (nonatomic, retain) UIImageView *gifImageView;
@end

@implementation XDDetailsViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
//    self.tabBarController.tabBar.hidden = YES;
    [self getData];
    self.title = self.name;
    [self yangTuo];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[[UIImage imageNamed:@"back"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] style:UIBarButtonItemStyleDone target:self action:@selector(back)];
    

//    self.navigationItem.rightBarButtonItem = [[[UIBarButtonItem alloc]initWithTitle:@"收藏" style:UIBarButtonItemStyleDone target:self action:@selector(rightAction:)]autorelease];
    
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[[UIImage imageNamed:@"iconfont-shoucang"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] style:UIBarButtonItemStyleDone target:self action:@selector(rightAction:)];
    
    
    //创建数据库单例对象
    self.dbManager = [XDRecommendDateBaseManager shareInstance];
//    //打开数据库
//    [_dbManager openDB];
    //创建表
    [_dbManager createTable];
    
}
- (void)rightAction:(UINavigationItem *)right
{
    //查询
    NSMutableArray *arr = [_dbManager selectInfo];
    NSInteger aa = 0;
    for (XDRecommend *recommend in arr) {
        if ([recommend.name isEqualToString:[self.title stringByReplacingOccurrencesOfString:@"'" withString:@" "]]) {
            aa = 1;
        }
    }
//    for (XDDetails *details in arr) {
//        if ([details.text isEqualToString:self.title]) {
//            aa = 1;
//        }
//    }

    if (aa == 0) {
        //插入数据
        XDRecommend *recom = [[XDRecommend alloc]init];
        recom.name = self.title;
        recom.ids = self.ids;
        recom.first_day = self.first_day;
        recom.day_count = self.day_count;
        recom.popular_place_str = self.popular_place_str;
        recom.cover_image = self.cover_image;
        [_dbManager insertInfoWithXDRecommend:recom];
        [recom release];
//        XDDetails *xdde = [[XDDetails alloc]init];
//        xdde.text = self.title;
//        [_dbManager insertInfoWithXDDetails:xdde];
//        [xdde release];

        UIAlertView *al1 = [[UIAlertView alloc]initWithTitle:@"提示" message:@"收藏成功" delegate:self cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
        [al1 show];
        [al1 release];
    }else{
        UIAlertView *al2 = [[UIAlertView alloc]initWithTitle:@"提示" message:@"已被收藏" delegate:self cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
        [al2 show];
        [al2 release];
    }

}

- (void)back
{
    [self.navigationController popViewControllerAnimated:YES];
    self.tabBarController.tabBar.hidden = NO;
}

- (void)yangTuo
{
    [self getData];
    self.gifImageView.hidden = NO;
    self.gifImageView = [[UIImageView alloc] initWithFrame:CGRectMake(self.view.frame.size.width / 2 - 40, self.view.frame.size.height / 2 - 50, 80, 100)];
    NSArray *gifArray = [NSArray arrayWithObjects:[UIImage imageNamed:@"cao1.png"],
                         [UIImage imageNamed:@"cao2.png"],
                         [UIImage imageNamed:@"cao3.png"],
                         [UIImage imageNamed:@"cao4.png"],
                         [UIImage imageNamed:@"cao5.png"],
                         [UIImage imageNamed:@"cao6.png"],
                         [UIImage imageNamed:@"cao7.png"],
                         [UIImage imageNamed:@"cao8.png"],
                         [UIImage imageNamed:@"cao9.png"],
                         [UIImage imageNamed:@"cao10.png"],nil];
    self.gifImageView.animationImages = gifArray; //动画图片数组
    self.gifImageView.animationDuration = 0.8; //执行一次完整动画所需的时长
    self.gifImageView.animationRepeatCount = 10000;  //动画重复次数
    [self.gifImageView startAnimating];
    [self.view addSubview:self.gifImageView];
    [self.gifImageView release];
}

- (void)getData
{
    self.array = [NSMutableArray array];
    NSMutableArray *arrarr = [NSMutableArray array];
    NSString *url = [NSString stringWithFormat:@"http://api.breadtrip.com/trips/%@/waypoints/",self.ids];
    [NetworkHandle getDataWithURL:url completion:^(id result) {
        NSArray *arr = [result objectForKey:@"days"];
        for (NSDictionary *dic in arr) {
            NSArray *rrr = [dic objectForKey:@"waypoints"];
            for (NSDictionary *dic in rrr) {
                [arrarr addObject:dic];
            }
        }
        for (NSDictionary *dic in arrarr) {
            XDDetails *xd = [[XDDetails alloc] init];
            [xd setValuesForKeysWithDictionary:dic];
            [self.array addObject:xd];
            [xd release];
        }
        //NSLog(@"1次");
//        NSLog(@"%@", [[self.array objectAtIndex:0] allKeys]);
        [self createCollectionView];
        [self.gifImageView stopAnimating];
        self.gifImageView.hidden = YES;
    }];
    //NSLog(@"%@", self.array);
    
}

- (void)viewWillAppear:(BOOL)animated
{
    self.navigationController.navigationBarHidden = NO;
    [self.view setBackgroundColor:[UIColor whiteColor]];
    NSIndexPath *path = [NSIndexPath indexPathForItem:self.number_photo inSection:0];
    [self.collectionView scrollToItemAtIndexPath:path atScrollPosition:UICollectionViewScrollPositionTop animated:YES];
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    CGFloat x = 0;
    CGFloat y = 0;
    if ([[self.array objectAtIndex:indexPath.row] photo_info] == nil) {
        x = self.view.frame.size.width - 30;
        y = 200;
    }
    else
    {
        x = [[[[self.array objectAtIndex:indexPath.row] photo_info] objectForKey:@"h"] integerValue];
        y = [[[[self.array objectAtIndex:indexPath.row] photo_info] objectForKey:@"w"] integerValue];
    }
    if ([[[self.array objectAtIndex:indexPath.row] photo] length] <= 3) {
        x = 0;
        y = 1;
    }
    NSString *name_text = [self.array[indexPath.row] text];
    CGFloat ff = [[self class] hightWithText:name_text];
    NSInteger h = (self.view.frame.size.width - 30) / y * x;
    return CGSizeMake(self.view.frame.size.width, h + 20 + ff);
}

+ (CGFloat)hightWithText:(NSString *)textName
{
    NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:[UIFont systemFontOfSize:13], NSFontAttributeName, nil];
    CGSize size = CGSizeMake([UIScreen mainScreen].bounds.size.width, 5000);
    CGRect rect = [textName  boundingRectWithSize:size options:NSStringDrawingUsesLineFragmentOrigin attributes:dic context:nil];
    return rect.size.height;
}

-(void)createCollectionView
{
    UICollectionViewFlowLayout *flowLayout = [[[UICollectionViewFlowLayout alloc]init]autorelease];
    //item的大小
    flowLayout.itemSize = CGSizeMake(self.view.frame.size.width, self.view.frame.size.height / 3 + 180);
    //item最小行间距
    flowLayout.minimumLineSpacing = 30;
    
    self.collectionView = [[[UICollectionView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height + 49) collectionViewLayout:flowLayout]autorelease];
    _collectionView.delegate = self;
    _collectionView.dataSource = self;
    //关闭边缘弹动
//    _collectionView.bounces = NO;
    //背景颜色
    _collectionView.backgroundColor = [UIColor colorWithRed:245 / 255.0 green:248 / 255.0 blue:240 / 255.0 alpha:1];
    [self.view addSubview:_collectionView];
    //collectionView创建时 必须先注册一个cell
    [self.collectionView registerClass:[XDReconmmendCollectionViewCell class] forCellWithReuseIdentifier:@"cell"];
}

-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    //NSLog(@"count-%ld", self.array.count);
    return self.array.count;
}


-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    XDReconmmendCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"cell" forIndexPath:indexPath];
    XDDetails *D = self.array[indexPath.row];
    cell.details = D;
//    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tap)];
//    [cell.pic addGestureRecognizer:tap];
    return cell;
    
}

- (void)tap
{
    NSLog(@"789");
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    XDPhotoTextViewController *xd = [[XDPhotoTextViewController alloc] init];
    xd.photo_text_details = self.array;
    xd.number_photo = indexPath.row;
    xd.delegate = self;
//    self.collectionView.contentScaleFactor = indexPath.row;
    [self.navigationController pushViewController:xd animated:YES];
}

- (void)get:(NSInteger)number
{
    self.number_photo = number;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
